package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.common.web.BaseController;
import com.antdesignbackend.backend.entity.EarMark;
import com.antdesignbackend.backend.entity.EntryRecord;
import com.antdesignbackend.backend.entity.SlaughterRecord;
import com.antdesignbackend.backend.entity.entityVo.EntryRecordVo;
import com.antdesignbackend.backend.entity.entityVo.SlaughterRecordVo;
import com.antdesignbackend.backend.service.EarMarkService;
import com.antdesignbackend.backend.service.EntryRecordService;
import com.antdesignbackend.backend.service.SlaughterRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/slaughterRecord")
public class SlaughterRecordController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SlaughterRecordService slaughterRecordService;
    @Autowired
    EarMarkService earMarkService;
    @Autowired
    EntryRecordService entryRecordService;
    /**
     *屠宰记录
     */
    @GetMapping("/index")
    @AuthToken
    public String index() {
        return "records/slaughterRecord/index";
    }

    /**
     * 表格查询
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody SlaughterRecordVo slaughterRecordVo) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        ReturnVO result = new ReturnVO();
        List<SlaughterRecordVo> slaughterRecordVos=new ArrayList<>();
        QueryWrapper<SlaughterRecordVo> wrapper =new QueryWrapper<>();
        if(slaughterRecordVo.getSourceAddress()!=null&& !slaughterRecordVo.getSourceAddress().equals(""))
        {
            wrapper.like("a.sourceAddress",slaughterRecordVo.getSourceAddress());
        }
        if (slaughterRecordVo.getTimeInterval() != null && !slaughterRecordVo.getTimeInterval().equals("")){
            String[] str=slaughterRecordVo.getTimeInterval().split(" - ");
            String star=str[0];
            String end=str[1];
            wrapper.between("a.entryDate",star,end);
        }
        wrapper.orderByDesc("a.entryDate").orderByDesc("d.SlaughterDate");
        wrapper.eq("d.eid",getLoginEnterpriseId());
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=slaughterRecordService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>=0)
        {
            slaughterRecordVos=slaughterRecordService.search(wrapper,new Page<>(slaughterRecordVo.getPageIndex(),slaughterRecordVo.getPageSize()));
        }
        result.setData(slaughterRecordVos);
        return result;
    }

    //屠宰记录保存
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody SlaughterRecord slaughterRecord) throws Exception {
        ReturnVO result = new ReturnVO();
        Boolean b = false;
        //修改存栏数
        EntryRecord entryRecord = entryRecordService.getById(slaughterRecord.getEntryRecordId());
        if (entryRecord == null){
            result.setMessage("保存失败！");
            result.setCode("500");
            return result;
        }else {
            //判断数量
            if (slaughterRecord.getSlaughterNumber() > entryRecord.getLivestock()){
                result.setMessage("压栏数不足！");
                result.setCode("501");
                return result;
            }
        }
        int livestock = entryRecord.getLivestock() - slaughterRecord.getSlaughterNumber();
        UpdateWrapper<EntryRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("livestock",livestock).eq("id",slaughterRecord.getEntryRecordId());
        b = entryRecordService.update(updateWrapper);
        if (b){
            slaughterRecord.setEid(getLoginEnterpriseId());
            b = slaughterRecordService.save(slaughterRecord);
        }
        if(b){
            result.setMessage("保存成功！");
            result.setCode("200");
        }else{
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    @PostMapping("/tableSearchMe/{eid}")
    @ResponseBody
    public ReturnVO tableSearchMe(@PathVariable("eid") int eid) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        ReturnVO result = new ReturnVO();
        List<SlaughterRecordVo> slaughterRecordVos=new ArrayList<>();
        QueryWrapper<SlaughterRecordVo> wrapper =new QueryWrapper<>();
        SlaughterRecordVo slaughterRecordVo=new SlaughterRecordVo();
        wrapper.eq("a.eid",eid);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=slaughterRecordService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>=0)
        {
            slaughterRecordVos=slaughterRecordService.search(wrapper,new Page<>(slaughterRecordVo.getPageIndex(),slaughterRecordVo.getPageSize()));
        }
        result.setData(slaughterRecordVos);
        return result;
    }
}
